package com.macro.mall.tiny.modules.foster.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.utils.EmailUtil;
import com.macro.mall.tiny.constants.RedisConstant;
import com.macro.mall.tiny.modules.foster.mapper.UserMapper;
import com.macro.mall.tiny.modules.foster.model.User;
import com.macro.mall.tiny.modules.foster.model.dto.EmailDTO;
import com.macro.mall.tiny.modules.foster.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author ZhuYi
 * @create 2024/3/26 20:31
 */
@Service
public class EmailServiceImpl implements EmailService {
    private static final Logger LOGGER = LoggerFactory.getLogger(EmailServiceImpl.class);
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    /**
     * 邮箱发送验证码
     *
     * @param email
     * @return
     */
    @Override
    public CommonResult sendAuthCode(String email) {
        //检查是否已经发过验证码
        String codeCheck = (String) redisTemplate.opsForValue().get(RedisConstant.AUTH_CODE_KEY + email);
        if (codeCheck!= null) {
            return CommonResult.authCodeHasExist();
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .eq("email", email);
        User user = userMapper.selectOne(wrapper);
        if (user != null) {
            return CommonResult.phoneHasExist();
        }
        String code = creatMailCode();
        EmailDTO emailDTO = new EmailDTO();
        emailDTO.setTitle("验证码");
        emailDTO.setContent("【xx宠物寄养】验证码：" + code + "，10分钟内有效。验证码提供给他人可能导致账号被盗，请勿泄露，谨防被骗");
        emailDTO.setEmail(email);
        EmailUtil.sendEmail(emailDTO);
        redisTemplate.opsForValue().set(RedisConstant.AUTH_CODE_KEY + email, code,RedisConstant.AUTH_CODE_EXPIRE, TimeUnit.MINUTES);
        LOGGER.info("验证码：{},已发送",redisTemplate.opsForValue().get(RedisConstant.AUTH_CODE_KEY + email));
        return CommonResult.success("已发送");
    }

    /**
     * description:生成邮箱验证码
     *
     * @return String
     * @author zhuyi
     */
    private String creatMailCode() {
        StringBuilder sb = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(rand.nextInt(10));
        }
        return sb.toString();
    }

}
